package jxau.jwgl.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Json数据处理工具(jackson实现)
 *
 * @author longshu 2017/06/09
 */
public final class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)// null属性值不映射
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);//有属性不能映射的时候不报错
    }

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    public static String toJson(Object object) {
        return toJson(object, false);
    }

    public static String toJson(Object object, boolean pretty) {
        try {
            if (pretty) {
                return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
            } else {
                return objectMapper.writeValueAsString(object);
            }
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static void toJson(OutputStream out, Object object) throws IOException {
        toJson(out, object, false);
    }

    public static void toJson(OutputStream out, Object object, boolean pretty) throws IOException {
        try {
            if (pretty) {
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(out, object);
            } else {
                objectMapper.writeValue(out, object);
            }
        } finally {
            out.flush();
            out.close();
        }
    }

    public static void toJson(File dest, Object object) throws IOException {
        toJson(new FileOutputStream(dest), object);
    }

    public static void toJson(File dest, Object object, boolean pretty) throws IOException {
        toJson(new FileOutputStream(dest), object, pretty);
    }

    // ************************************************* //

    public static Object parse(String text) {
        return parse(text, Object.class);
    }

    public static <T> T parse(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            return null;
        }
    }

    public static <T> T parse(InputStream in, Class<T> clazz) throws IOException {
        return objectMapper.readValue(in, clazz);
    }

    public static <T> T parse(File src, Class<T> clazz) throws IOException {
        return objectMapper.readValue(src, clazz);
    }

}